package com.example.za.account.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.example.za.account.R;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.model.User;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.FileUtils;
import com.example.za.account.utils.L;
import com.example.za.account.utils.T;
import com.example.za.account.view.CircleImageView;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;


public class UserActivity extends BaseActivity {

    private static final int FROM_CAMERA = 0x1;
    private static final int FROM_GALLERY = 0x2;
    private static final int CROP_PHOTO = 0x3;
    private static final int MODIFY_NAME = 0X4;
    private Uri mCropPhoto;
    private Uri mTakePhoto;
    private File mTempPic;
    private String mNewName;
    private String mNewFileName;
    BmobFile bmobFile;
    @BindView(R.id.iv_user_photo)
    CircleImageView ivUserPhoto;
    @BindView(R.id.info_username)
    TextView infoUsername;
    private BmobUser user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        ButterKnife.bind(this);
        setTitle(getString(R.string.person_info));
        showBackwardView(true);
        user = BmobUser.getCurrentUser(User.class);
        infoUsername.setText(user.getUsername());

        User user1 = (User) user;
        L.e(getExternalFilesDir(null) + File.separator + user.getObjectId()
                + File.separator + user1.getmPicture());
        if (user1.getmPicture() != null) {
            ivUserPhoto.setImageBitmap(BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator
                    + user.getObjectId() + File.separator + user1.getmPicture()));
        }

    }

    @Override
    protected Activity getSubActivity() {
        return this;
    }

    @OnClick({R.id.ll_info_photo, R.id.ll_info_name, R.id.ll_info_pass, R.id.btn_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_info_photo:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setItems(new String[]{"拍照", "图库"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: {
                                mTakePhoto = Uri.fromFile(new File(getExternalCacheDir() +
                                        File.separator + "IMG_" + System.currentTimeMillis() + ".jpg"));
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhoto);
                                startActivityForResult(intent, FROM_CAMERA);
                            }
                            break;
                            case 1: {
                                getCropUri();
                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                intent.putExtra("crop", "true");
                                intent.putExtra("aspectX", 1);// 裁剪框比例
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 100);// 输出图片大小
                                intent.putExtra("outputY", 100);
                                intent.putExtra("scale", true);
                                intent.putExtra("return-data", false);
                                intent.putExtra("outputFormat", "JPEG");
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, mCropPhoto);
                                intent.putExtra("noFaceDetection", true);
                                startActivityForResult(intent, FROM_GALLERY);
                            }
                            break;

                        }
                    }
                });
                builder.show();
                break;
            case R.id.ll_info_name:
                startActivityForResult(new Intent(this, NameActivity.class), MODIFY_NAME);
                break;
            case R.id.ll_info_pass:
                startActivity(new Intent(this, PasswordActivity.class));
                break;
            case R.id.btn_logout: {
                BmobUser.logOut();
                AccountApplication.sUser = null;
                startActivity(new Intent(this, LoginActivity.class));
                sendBroadcast(new Intent(Constant.ACTION_FINISH));
                finish();
            }
            break;
        }
    }

    private void getCropUri() {
        mTempPic = new File(getExternalCacheDir() + File.separator + "Crop_"
                + System.currentTimeMillis() + ".jpg");
        mCropPhoto = Uri.fromFile(mTempPic);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == MODIFY_NAME) {
                mNewName = data.getStringExtra(Constant.NEW_USERNAME);
                infoUsername.setText(mNewName);
            } else if (requestCode == CROP_PHOTO || requestCode == FROM_GALLERY) {
                if (mCropPhoto != null) {
                    Bitmap bitmap = getBitmapFromUri(mCropPhoto);
                    ivUserPhoto.setImageBitmap(bitmap);
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            bmobFile = new BmobFile(mTempPic);


                            bmobFile.uploadblock(new UploadFileListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        //bmobFile.getFileUrl()--返回的上传文件的完整地址

//                                        T.showShort(UserActivity.this, "上传文件成功:" + bmobFile.getFileUrl());

                                        //上传成功后保存url
                                        SharedPreferences sharedPreferences = getSharedPreferences("FileUrl", Context.MODE_PRIVATE); //私有数据
                                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                                        editor.putString("url", bmobFile.getFileUrl());
                                        editor.commit();//提交修改

                                        //加入本地缓存
                                        FileUtils.writeFile(mTempPic.getAbsolutePath(), getExternalFilesDir(null) + File.separator + user.getObjectId()
                                                + File.separator + bmobFile.getFilename());

                                        User user = new User();
                                        user.setmPicture(bmobFile.getFilename());
                                        user.update(BmobUser.getCurrentUser(User.class).getObjectId(), new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {
                                                if (e != null) {
                                                    T.showShort(UserActivity.this, getString(R.string.update_photo_fail));
                                                } else {
                                                    L.e("e != null");
                                                    mNewFileName = bmobFile.getFilename();
                                                    T.showShort(UserActivity.this, getString(R.string.update_photo_succeed));
                                                }
                                            }
                                        });

                                    } else {
                                        T.showShort(UserActivity.this, getString(R.string.upload_fail));
                                        L.e("上传图片:" + e.getMessage());
                                    }
                                }

                                @Override
                                public void onProgress(Integer value) {
                                    // 返回的上传进度（百分比）
                                }

                            });
                            return null;
                        }

                    }.execute();
                }
            } else if (requestCode == FROM_CAMERA) {
                cropImageUri(mTakePhoto);
            }

        }
    }

    @Override
    protected void onBackword() {
        Intent intent = new Intent();
        if (mNewName != null) {
            intent.putExtra(Constant.NEW_USERNAME, mNewName);
        }
        if (mNewFileName != null) {
            intent.putExtra(Constant.NEW_FILENAME, mNewFileName);
        }
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Intent intent = new Intent();
            if (mNewName != null) {
                intent.putExtra(Constant.NEW_USERNAME, mNewName);
            }
            if (mNewFileName != null) {
                intent.putExtra(Constant.NEW_FILENAME, mNewFileName);
            }
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            return MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void cropImageUri(Uri uri) {
        getCropUri();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("scale", true);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCropPhoto);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);
        startActivityForResult(intent, CROP_PHOTO);
    }

}
